package generic.util;

import java.util.HashSet;
import java.util.Set;

public class Sets {

    /**
     * 求并集
     * @param a 集合a
     * @param b 集合b
     * @return 并集
     */
    public static <T> Set<T> union(Set<T> a, Set<T> b) {
        Set<T> result = new HashSet<>(a);
        result.addAll(b);
        return result;
    }

    /**
     * 求交集
     * @param a 集合a
     * @param b 集合b
     * @param <T>
     * @return
     */
    public static <T> Set<T> intersection(Set<T> a, Set<T> b) {
        Set<T> result = new HashSet<>(a);
        result.retainAll(b);
        return result;
    }

    /**
     * 求差
     * @param superset
     * @param subset
     * @param <T>
     * @return
     */
    // Subtract subset from superset:
    public static <T> Set<T> difference(Set<T> superset, Set<T> subset) {
        Set<T> result = new HashSet<>(superset);
        result.removeAll(subset);
        return result;
    }

    /**
     * 求补集(并集减去交集)
     * @param a
     * @param b
     * @param <T>
     * @return
     */
    // Reflexive--everything not in the intersection:
    public static <T> Set<T> complement(Set<T> a, Set<T> b) {
        return difference(union(a, b), intersection(a, b));
    }
}
